package com.wangxiaonan.coupon.common;

import java.util.HashMap;
import org.springframework.http.HttpStatus;

/**
 * 返回对象包装类
 *
 * @Author: wangxiaonan
 * @Date: 2018/12/28
 **/
public class ResponseWrapper extends HashMap<String, Object> {

    private static final long serialVersionUID = -9127836989202638260L;
    private static final String RESULT_STATUS = "status";
    private static final String RESULT_MESSAGE = "message";
    private static final String RESULT_DATA = "data";
    private static final String RESULT_REDIRECT = "redirect";
    private static final String EMPTY_STRING = "";

    /**
     * 默认无成功和失败状态
     */
    public ResponseWrapper() {
        super();
    }

    public ResponseWrapper(HttpStatus status, String message) {
        super();

    }

    public boolean isSuccess() {
        return this.get(RESULT_STATUS) != null && this.get(RESULT_STATUS) == HttpStatus.OK;
    }

    public ResponseWrapper success() {
        this.put(RESULT_STATUS, HttpStatus.OK);
        return this;
    }

    public ResponseWrapper success(String message) {
        this.put(RESULT_MESSAGE, message);
        return this;
    }

    public ResponseWrapper success(String message, Object data) {
        this.put(RESULT_MESSAGE, message);
        this.put(RESULT_DATA, data);
        return this;
    }

    public ResponseWrapper status(HttpStatus status) {
        this.put(RESULT_STATUS, status.value());
        return this;
    }

    public ResponseWrapper fail(HttpStatus status) {
        this.put(RESULT_STATUS, status.value());
        return this;
    }

    public ResponseWrapper fail(HttpStatus status, String message) {
        this.put(RESULT_STATUS, status.value());
        this.put(RESULT_MESSAGE, message);
        return this;
    }

    public ResponseWrapper fail(HttpStatus status, String message, Object... args) {
        this.put(RESULT_STATUS, status.value());
        this.put(RESULT_MESSAGE, String.format(message, args));
        return this;
    }

    public String getMessage() {
        return String.valueOf(this.putIfAbsent(RESULT_MESSAGE, EMPTY_STRING));
    }

    public ResponseWrapper addMessage(String message) {
        this.put(RESULT_MESSAGE, message);
        return this;
    }

    public ResponseWrapper addData(Object data) {
        this.put(RESULT_DATA, data);
        return this;
    }

    public Object getData() {
        return this.get(RESULT_DATA);
    }

    public ResponseWrapper addRedirect(String url) {
        this.put(RESULT_REDIRECT, url);
        return this;
    }
}
